import * as vscode from 'vscode';
import { scanSnippets } from './utils/file';

// 获取工作区
const workspaceFolders = vscode.workspace.workspaceFolders as vscode.WorkspaceFolder[];
// 默认只支持第一个工作区
if (workspaceFolders?.[0].uri) {
  vscode.workspace.fs.readDirectory(workspaceFolders[0].uri).then((res) => {
    const templateIndex = res.findIndex(
      (item) => item[0] === '.snippets.template'
    );
    if (templateIndex === -1) {
      // 运行插件时会默认添加.snippets.template文件夹，用于存放模版文件
      vscode.workspace.fs.createDirectory(vscode.Uri.parse(workspaceFolders[0].uri.path+'/.snippets.template'));
    }
  });
}

export function activate(context: vscode.ExtensionContext) {
  console.log('Congratulations, your extension "snippet" is now active!');
  // 启动的时候扫描注册一下
  scanSnippets(context);

  // 更新代码块
  let disposable = vscode.commands.registerCommand('snippet.refresh', () => {
    // 将原有Snippet取消注册重新扫描
    const oldSnippets = context.subscriptions.splice(
      1,
      context.subscriptions.length - 1
    );
    oldSnippets.forEach((s) => s.dispose());
    scanSnippets(context);
    vscode.window.showInformationMessage('代码块文件更新成功！');
  });

  // 注册命令
  context.subscriptions.push(disposable);

  // 添加模板文件
  let addTemplate = vscode.commands.registerCommand(
    'snippet.addTemplate',
    async (data) => {
      // 获取模块名称
      const name = await vscode.window.showInputBox({
        placeHolder: '请输入模块名称',
      });
      if (name) {
        vscode.workspace.fs.readDirectory(data).then(async (res) => {
          const templateIndex = res.findIndex(
            (item) => item[0] === name
          );
          // 判断文件夹名称是否重名
          if(templateIndex === -1){
            const templateChildren = await vscode.workspace.fs.readDirectory(vscode.Uri.parse(workspaceFolders[0].uri.path+'/.snippets.template'));
            const pickItem = templateChildren.filter(item=>item[1] === 2).map(item=>item[0]);
            const currPick = await vscode.window.showQuickPick(pickItem);
            if(currPick){
              // 将选中的文件夹复制到目标文件夹中
              vscode.workspace.fs.copy(vscode.Uri.parse(workspaceFolders[0].uri.path+'/.snippets.template/'+currPick),vscode.Uri.parse(data.path+'/'+name));
            }
          }else{
            vscode.window.showErrorMessage(`${name}目录已存在！`);
          }
        });
      }
    }
  );

  context.subscriptions.push(addTemplate);
}

// this method is called when your extension is deactivated
export function deactivate() {}
